$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'new/order/list',
        datatype: "json",
        colModel: [
            {label: '订单id', name: 'orderId', width: 45, key: true, align: 'center', sortable: false},
            {label: '订单号', name: 'orderNo', width: 90, key: true, align: 'center', sortable: false},
            {
                label: '订单状态',
                name: 'orderState',
                width: 75,
                align: 'center',
                 sortable: false
            },
            {label: '商品名称', name: 'goodsName', width: 60, align: 'center', sortable: false},
            {label: '商品型号', name: 'model', width: 60, align: 'center', sortable: false},
            {label: '商品数量', name: 'goodsNumber', width: 45, align: 'center', sortable: false},
            {label: '总价', name: 'goodsPrice', width: 75, align: 'center', sortable: false},
            {
                label: '购入时间', name: 'byDate', width: 60, align: 'center', sortable: false
            },
            {label: '购买人', name: 'name', width: 75, align: 'center', sortable: false},
            {label: '购买人手机号', name: 'phone', width: 75, align: 'center'},
            {
                label: '操作', name: 'orderId', formatter: function (value, options, row) {
                    var str = '';
                    if (row.orderState == '待签收' || row.orderState == '已完成') {
                        str = '<span class = "btn btn-success btn-sm" onclick="detail('+value+')">详情</span>&nbsp;&nbsp;';
                    } else if(row.orderState == '待发货'){
                        str = '<span class = "btn btn-success btn-sm" onclick = "handle(' + value + ')">待划拨</span>&nbsp;&nbsp;';
                    }else if(row.orderState == '待付款' ){
                        str = '<span class = "btn btn-sm" >等待付款</span>&nbsp;&nbsp;';
                    } else {
                        str = '<span class = "btn btn-sm" >交易关闭</span>&nbsp;&nbsp;';
                    }

                    return str ;
                }, align: 'center', sortable: false
            }
        ],
        viewrecords: true,
        height: 450,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });

    bindType();
});

//增加终端输入区间
function addArea() {
    var text = "";
    text += "<tr>";
    text += " <td><label class=\"layui-form-label\">划拨机具:</label></td>";
    text += "<td><div class = \"layui-input-inline\" >";
    text += " <input  type = \"text\" class = \"layui-input startNo\"/></div>";
    text += "<div class = \"layui-input-inline\" > <label class= \"layui-form-label\" style=\"width:60px\">——</label></div>";
    text += "<div class = \"layui-input-inline\" >";
    text += " <input type = \"text\" class = \"layui-input endNo\"/>";
    text += " </div></td>";
    text += " </td><td><label class='btn btn-default' onClick=\"addArea()\">添加区间</label>";
    text += "<label class='btn btn-default' onClick=\"addOne()\">添加单个</label>";
    text += "<label class='btn btn-default' onClick=\"delThisEL(this)\">删除此条</label></td> </tr>";
    $("#terInput").append(text);
}

//增加单个终端输入框
function addOne() {
    var text = "";
    text += "<tr>";
    text += "<td><label class=\"layui-form-label\" style='width: 95px'>划拨机具:</label></td>";
    text += "<td><div class=\"layui-input-inline\">";
    text += "<input type=\"text\" class=\"layui-input aloneNo\" />";
    text += "</div></td>";
    text += "</td><td><label class='btn btn-default' onClick=\"addArea()\">添加区间</label>";
    text += "<label class='btn btn-default' onClick=\"addOne()\">添加单个</label>";
    text += "<label class='btn btn-default' onClick=\"delThisEL(this)\">删除此条</label></td> </tr>";
    $("#terInput").append(text);
}

//删除
function delThisEL(obj) {
    let count = $("#terInput tr").length;
    if (count == 1) {
        layer.msg("不能再继续删除了");
        return;
    }
    $(obj).parents("tr").remove();
    collectInfo();
}

//获得信息
function collectInfo() {
    let startels = document.querySelectorAll(".startNo");
    let endels = document.querySelectorAll(".endNo");
    let aloneEls = document.querySelectorAll(".aloneNo");
    //初始化数组
    vm.params.startArray=[];
    vm.params.endArray=[];
    vm.params.aloneArray=[];
    for (let i = 0; i < startels.length; i++) {
        if (startels[i].value == null || startels[i].value == '') {
            layer.msg("请填写开始终端号");
            return;
        }
        vm.$set(vm.params.startArray, i, startels[i].value);
    }
    for (let i = 0; i < endels.length; i++) {
        if (endels[i].value == null || endels[i].value == '') {
            layer.msg("请填写结束终端号");
            return;
        }
        vm.$set(vm.params.endArray, i, endels[i].value);
    }

    for (let i = 0; i < aloneEls.length; i++) {
        if (aloneEls[i].value == null || aloneEls[i].value == '') {
            layer.msg("请填写单独终端号");
            return;
        }
        vm.$set(vm.params.aloneArray, i, aloneEls[i].value);
    }
    let str = {
        "startArray": vm.params.startArray,
        "endArray": vm.params.endArray,
        "aloneArray": vm.params.aloneArray,
        "terminalType": vm.params.terminalType,
        "reapAmount": vm.params.reapAmount,
        "logisticId": vm.params.logisticId,
        "logisticCode": vm.params.logisticCode,
        "dueDate":vm.params.dueDate,
        "afterCash":vm.params.afterCash
    };
    return str;
}

//处理订单
function handle(orderId) {
    //打开弹窗前初始化
    vm.params = {
        startArray: [],
        endArray: [],
        aloneArray: [],
        agentId: null,
        terminalType: 0,
        reapAmount: null,
        logisticCode: null,
        logisticId: 0,
        orderId: null,
        isOnline: 1,
        dueDate:null,
        afterCash:null
    };
    queryAddress(orderId);//查询地址
    bindLogistics();//绑定物流下拉框

    //添加区间
    document.querySelector("#terInput").innerHTML = "";
    addArea();
    let index = layer.open({
        type: 1,
        title: "处理订单",
        content: $("#handle"),
        area: ['850px', '600px'],
        btn: ['划拨', '取消'],
        btn1: function () {
            let str = collectInfo();
            if (str.terminalType == null || str.terminalType == 0) {
                layer.msg("请选择机具类型");
                return;
            }

            if($("input[name='amount']").is(':visible') && str.terminalType!=6){
                if ((str.reapAmount == null || str.reapAmount==0) ) {
                    layer.msg("请填写返现金额");
                    return;
                }
            }

            vm.params.agentId = vm.address.agentId;
            vm.params.orderId = orderId;
            $.ajax({
                url: baseURL + "new/order/handleOrder",
                type: "post",
                contentType: "application/json",
                data: JSON.stringify(vm.params),
                beforeSend:function(){
                    var index=layer.load(2,{
                        shade: [0.8,'#fff']
                    });
                },
                complete:function(){
                    layer.close(index);
                },
                success: function (r) {
                    if (r.code == 0) {
                        alert(r.msg);
                        layer.close(index);
                        vm.reload();
                    } else {
                        alert(r.msg)
                    }
                }
            })
        }
    })
}

//查询地址
function queryAddress(orderId) {
    $.get(baseURL + "new/order/queryAddress/" + orderId,  (result)=> {
        vm.address = result.address;
    })
}

//删除订单
function delOrder(orderId) {
    /*confirm("确定要删除该订单？", function () {
        $.ajax({
            type: "POST",
            url: baseURL + "new/order/deleteOrder",
            dataType: "json",
            data: {"orderId": orderId},
            success: function (r) {
                if (r.code == 0) {
                    alert('操作成功', function () {
                        vm.reload();
                    });
                } else {
                    alert(r.msg);
                }
            }
        });
    });*/
}


var vm = new Vue({
    el: '#rrapp',
    data: {
        q: {
            model: null,
            byDate: null,
            phone: null,
            orderState: "",
            orderId:null
        },
        models: [],
        showList: true,
        title: null,
        address: {
            agentId: null,
            nick: null,
            phone: null,
            prov: null,
            city: null,
            area: null,
            info: null,
        },
        params: {
            startArray: [],
            endArray: [],
            aloneArray: [],
            agentId: null,
            terminalType: 0,
            reapAmount: null,
            logisticId: 0,
            logisticCode: null,
            orderId: null,
            isOnline: 1,
            dueDate:null,
            afterCash:null
        },
        terminalTypes: [],
        logistices: [],
        orderState:[
            {
                value:"",
                name:"订单状态"
            },{
                value:"0",
                name:"待付款"
            },{
                value:"1",
                name:"待发货"
            },{
                value:"2",
                name:"待签收"
            },{
                value:"3",
                name:"已完成"
            },{
                value:"-1",
                name:"交易关闭"
            },
        ]
    },
    methods: {
        query: function () {
            vm.reload();
        },
        clean: function () {
            vm.showList = true;
            vm.q = {
                model: null,
                byDate: null,
                phone: null,
                orderState: "",
                orderId:null
            };
            $("#jqGrid").jqGrid('setGridParam', {'page': 1});
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
        },
        reload: function () {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'model': vm.q.model,
                    'byDate': vm.q.byDate,
                    'phone': vm.q.phone,
                    "orderState": vm.q.orderState,
                    'orderId':vm.q.orderId
                },
                page: page
            }).trigger("reloadGrid");
        },

    }
});


//绑定终端类型下拉框
function bindType() {

        $.getJSON(baseURL + "sys/terminalType/list", function (r) {
            vm.$set(vm.terminalTypes, 0, {
                terminalType: 0,
                terminalName: "请选择类型"
            });
            for (var i = 0; i < r.page.length; i++) {
                vm.$set(vm.terminalTypes, (i + 1), r.page[i]);
            }

        })

}

//绑定物流下拉框
function bindLogistics() {
    $.getJSON(baseURL + "new/order/queryLogisticList/", function (r) {
        vm.$set(vm.logistices, 0, {
            logisticId: 0,
            logisticName: "直接选择或搜索选择"
        });
        for (var i = 0; i < r.list.length; i++) {
            vm.$set(vm.logistices, (i + 1), r.list[i]);
        }
        vm.params.logisticId = 0;
    });
    layui.use('form', function () {
        let form = layui.form;

        form.on('select(type)', function (data) {//对应拉卡拉 value=4 ,不允许填写返现金额
            vm.params.terminalType = data.value;
            if (data.value == 6) {
                $("input[name='amount']").attr("disabled", true);
                $("input[name='amount']").addClass("layui-disabled");

            } else {
                $("input[name='amount']").removeAttr("disabled");
                $("input[name='amount']").removeClass("layui-disabled");
            }
        });
        form.on('select(logis)', function (data) { //赋值 vue 和layui绑定冲突 所以手动赋值
            vm.params.logisticId = data.value;
        });
        form.on('checkbox(isonline)', function (data) {
            //控制是否展示返现金额
            if(data.elem.checked){
                vm.params.isOnline=1;
                $("#upperform").css("width","90%");
                $(".amount").show();
            }else {
                $("#upperform").css("width","50%");
                $(".amount").hide();
                vm.params.isOnline=0
            }
        })

    });
}
//查询分配详情
function detail(orderId) {
    $.get(baseURL+"new/order/queryNoticeDetail/"+orderId,(r)=>{
            if(r.result.list.length==0){
                layer.msg("无详细信息")
            }else{
                detailObj.result=r.result;
                openDetail();
            }
    })


}

var detailObj=new Vue({
    el: '#detail',
    data: {
        result:{
            disSysAgent:{
                name:null
            },
            acceptSysAgent:{
                name:null
            },
            list:[],
            logisticsName:null,
            logisticsNum:null
        }
    }
});
//打开详情面板
function openDetail() {
    layer.open({
        type:1,
        title:'分配详情',
        content:$("#detail"),
        area:['600px','360px'],
        btn:['确定'],
        btn1:function(index){
          layer.close(index)
        }

    })
}